package com.example.dnfgamercommunitybackend.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.dnfgamercommunitybackend.entity.LoginAccount;
import com.example.dnfgamercommunitybackend.entity.ResponseResult;
import com.example.dnfgamercommunitybackend.util.JwtUtil;
import com.example.dnfgamercommunitybackend.util.RedisUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisUtil redisUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
        }else{
            //解析token，获取用户id
            String id = jwtUtil.getUserIdFromToken(token);
            //从redis中获取用户信息
            LoginAccount loginAccount = (LoginAccount) redisUtil.get("login:"+id);
            if (Objects.isNull(loginAccount)){
                throw new RuntimeException("用户未登录");
            }
            // TODO 获取权限信息封装到usernamePasswordAuthenticationToken
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(loginAccount,null,loginAccount.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            filterChain.doFilter(request,response);
        }
    }
}
